package com.bingxue.edu.migration.pay;

import cn.dev33.satoken.annotation.SaIgnore;
import cn.hutool.core.io.IoUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.bingxue.edu.common.config.FuiouPayProperties;
import com.bingxue.edu.common.util.FuiouPaySignUtil;
import com.bingxue.edu.framework.common.model.PageQuery;
import com.bingxue.edu.framework.common.model.Pagination;
import com.bingxue.edu.framework.common.model.Response;
import com.bingxue.edu.framework.common.util.CheckUtils;
import com.bingxue.edu.framework.mybatis.query.QueryBuilder;
import com.bingxue.edu.framework.security.ApiResource;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.Mapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;

/**
 * 临时支付记录接口
 *
 * @author panbo
 * @since 2024/09/19 14:16
 */
@Slf4j
@Tag(name = "临时支付记录接口")
@RestController
@RequestMapping("/temp/pay")
@RequiredArgsConstructor
public class TempPayRecordController {

    private final FuiouPayProperties fuiouPayProperties;
    private final TempPayRecordService tempPayRecordService;

    @Operation(description = "分页查询列表")
    @ApiResource("temp:pay:read")
    @GetMapping("/page")
    public Response<Pagination<TempPayRecord>> page(TempPayRecordQuery query, @Validated PageQuery pageQuery) {
        QueryWrapper queryWrapper = QueryBuilder.build(query, pageQuery);
        Page<TempPayRecord> page = tempPayRecordService.page(pageQuery.toPage(), queryWrapper);
        return Response.success(Pagination.of(page));
    }

    @Operation(description = "查询详情")
    @ApiResource("temp:pay:read")
    @GetMapping("/detail/{id}")
    public Response<TempPayRecord> detail(@PathVariable String id) {
        TempPayRecord detail = tempPayRecordService.getMapper().selectOneById(id);
        return Response.success(detail);
    }

    @SaIgnore
    @Operation(description="创建续报订单")
//    @ApiResource("temp:pay:write")
    @PostMapping("/create")
    public Response<Object> pay(@RequestBody @Validated TempPayRecordReq req) {
        req.setActualTotalPrice(computePrice(req));
        req.setOriginalTotalPrice(computePrice(req));
        return Response.success(tempPayRecordService.createPayOrder(req));
    }

    @Operation(description="支付回调")
    @SaIgnore
    @PostMapping("/callback")
    public Response<Void> callback(HttpServletRequest request) throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(request.getInputStream(), StandardCharsets.UTF_8));
        String body = IoUtil.read(reader);
        log.info("支付回调body: {}", body);
        JSONObject result = JSONUtil.parseObj(body);
        CheckUtils.throwIfNotEqual(result.get("resp_code"), "0000", "富友支付回调出错, body: {} ", body);
        String message = FuiouPaySignUtil.decryptByRsaPri(result.getStr("message"), fuiouPayProperties.getMchntPrivateKey(), "GBK");
        tempPayRecordService.completePay(new JSONObject(message));
        return Response.success();
    }

    @Operation(description="查询支付结果")
    @SaIgnore
    @GetMapping("/query/{orderId}")
    public Response<JSONObject> queryPayResult(@PathVariable String orderId) {
        return Response.success(tempPayRecordService.queryPayResult(orderId));
    }

    @Operation(description="更新数据")
    @ApiResource("temp:pay:write")
    @PostMapping("/update/{id}")
    public Response<Void> update(@RequestBody @Validated TempPayRecord req, @PathVariable String id) {
        TempPayRecord TempPayRecord = tempPayRecordService.copyById(req, id);
        tempPayRecordService.updateById(TempPayRecord);
        return Response.success();
    }

    private BigDecimal computePrice(TempPayRecordReq req) {
        return switch (req.getGrade()) {
            case "1", "2" -> BigDecimal.valueOf(2400);
            case "6" -> BigDecimal.valueOf(2320);
            default -> BigDecimal.valueOf(3120);
        };
    }
}
